package network

import (
	"sync"
)

// 收发包对象池

var (
	_recvpool   = NewRecvPackPool()
	GetRecvPack = _recvpool.Get
	PutRecvPack = _recvpool.Put

	_sendpool   = NewSendPackPool()
	GetSendPack = _sendpool.Get
	PutSendPack = _sendpool.Put
)

//recv pool

type RecvPackPool struct {
	p *sync.Pool
}

func NewRecvPackPool() RecvPackPool {
	return RecvPackPool{p: &sync.Pool{
		New: func() interface{} {
			return &Packet{}
		},
	}}
}

func (m *RecvPackPool) Get(l int) *Packet {
	p := m.p.Get().(*Packet)

	if p.Data == nil || p.slen < l {
		p.Data = make([]byte, l)
		p.slen = l
	} else {
		p.Data = p.Data[:l] // 需要固定长度
	}

	return p
}

func (m *RecvPackPool) Put(p *Packet) {
	if len(p.Data) > p.slen {
		p.slen = len(p.Data) // 重新分配过的
	} else if len(p.Data) < p.slen {
		p.Data = p.Data[:p.slen] // 还原
	}
	m.p.Put(p)
}

//send pool

type SendPackPool struct {
	p *sync.Pool
}

func NewSendPackPool() SendPackPool {
	return SendPackPool{p: &sync.Pool{
		New: func() interface{} {
			return &SendPacket{}
		},
	}}
}

func (m *SendPackPool) Get(l int) *SendPacket {
	p := m.p.Get().(*SendPacket)

	if p.Data == nil || len(p.Data) < l {
		p.Data = make([]byte, l)
		p.slen = l
	}
	return p
}

func (m *SendPackPool) Put(p *SendPacket) {
	if len(p.Data) > p.slen {
		p.slen = len(p.Data) // 重新分配过的
	} else if len(p.Data) < p.slen {
		p.Data = p.Data[:p.slen] // 还原
	}
	m.p.Put(p)
}

// end
